/** 
 * @Title:
 * @Desription:
 * @Company:CSN
 * @ClassName:Utils
 * @Author:林威
 * @CreateDate:2015年4月21日
 * @UpdateUser:林威
 * @Version:0.1
 *    
 */ 
package linwei.ce;

 /** 
 * @ClassName: Utils
 * @Description: 
 * @author: 林威
 * @date: 2015年4月21日
 * 
 */
public class Utils {
	/**
	 * 从字节流里读取int类型数据，大端存储
	 * @param bytes
	 * @return
	 */
	public static int toInt(byte[] bytes){
		return toInt(bytes, 0, bytes.length);
	}
	
	
	/**
	 * 从字节流里读取int类型数据，大端存储
	 * @param bytes
	 * @param start
	 * @param length
	 * @return
	 */
	public static int toInt(byte[] bytes, int start, int length){
		if (length == 1) {
			return ((int) bytes[start]) & 0x000000FF;
			
		} else if (length == 2) {
			return (((int) bytes[start] << 8) & 0x0000FF00) | (((int) bytes[start + 1]) & 0x000000FF);
			
		} else if (length == 4) {
			return (((int) bytes[start] << 24) & 0xFF000000) 
					| (((int) bytes[start + 1] << 16) & 0x00FF0000)
					| (((int) bytes[start + 2] << 8) & 0x0000FF00)
					| (((int) bytes[start + 3]) & 0x000000FF);
		}
		throw new IllegalArgumentException();
	}
	
	/**
	 * 从字节流里读取long型数据，大端存储
	 * @param bytes
	 * @param start
	 * @param length
	 * @return
	 */
	public static long toLong(byte[] bytes){
		return toLong(bytes, 0, bytes.length);
	}
	
	/**
	 * 从字节流里读取long型数据，大端存储
	 * @param bytes
	 * @param start
	 * @param length
	 * @return
	 */
	public static long toLong(byte[] bytes, int start, int length){
		if (length == 8){
			return ((long)bytes[start] << 56) 
					| ((long)bytes[start + 1] << 48 & 0x00FF000000000000L)
					| ((long)bytes[start + 2] << 40 & 0x0000FF0000000000L)
					| ((long)bytes[start + 3] << 32 & 0x000000FF00000000L)
					| ((long)bytes[start + 4] << 24 & 0x00000000FF000000L)
					| ((long)bytes[start + 5] << 16 & 0x0000000000FF0000L)
					| ((long)bytes[start + 6] << 8 & 0x000000000000FF00L)
					| ((long)bytes[start + 7] & 0x00000000000000FFL);
		}
		throw new IllegalArgumentException();
	}
}
